// 压力情景测试
import React from 'react';
import { connect } from 'dva';
import { TableC, XYAxisChartsC, NoQueryC } from '../../comps';
class StressTest extends React.Component {
  constructor() {
    super();
    this.state = {
      needRefresh: true,
      searchObj: undefined,
      dataSource: [],
      total: 0,
      columns: [
        { title: '资产类别', key: 'assetType', dataIndex: 'assetType' },
        { title: '证券代码', key: 'tradingCode', dataIndex: 'tradingCode' },
        { title: '证券简称', key: 'secuabbr', dataIndex: 'secuabbr' },
        { title: '面额', key: 'denomination', dataIndex: 'denomination' },
        { title: '期初全价市值', key: 'startFullValue', dataIndex: 'startFullValue' },
        { title: '期末全价市值', key: 'endFullValue', dataIndex: 'endFullValue' },
        { title: '预期收益率曲线上移损失', key: 'expectYieldLoss', dataIndex: 'expectYieldLoss' },
        { title: '预期债券违约损失', key: 'expectBondLoss', dataIndex: 'expectBondLoss' },
        { title: '预期指数下跌损失', key: 'expectIndexLoss', dataIndex: 'expectIndexLoss' },
        { title: '预期总损失', key: 'expectLoss', dataIndex: 'expectLoss' },
      ],
      series: [],
      xAxis: [],
      count: false, //是否开始计算
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    if (this.props.sceneType == 1) {
      this.getTableData();
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.info) != JSON.stringify(this.props.info)) {
    }
  }

  // 获取情景表格数据
  getTableData = () => {
    this.props.dispatch({
      type: `stressSceneTestM/getStressTestList`,
      payload: {
        ...this.props.searchObj,
        type: this.props.activeKey,
      },
      callback: (data) => {
        this.handleData(data);
      },
    });
  };

  // 获取个券表格数据
  getBondTableData = (dataSource, productCode, date) => {
    this.props.dispatch({
      type: `stressSceneTestM/getBondStressTestList`,
      payload: {
        productCode: productCode,
        date: date,
        dataSource: dataSource,
      },
      callback: (data) => {
        this.setState({
          count: true,
        });
        this.props.changeLoading();
        this.handleData(data);
      },
    });
  };

  // 个券重新查询
  setCount = (e) => {
    this.setState({
      count: e,
    });
  };

  //处理接口数据
  handleData = (data) => {
    let expandedRowKeys = [];
    let series = [
      {
        name: '收益率曲线上移',
        data: [],
      },
      {
        name: '债券违约',
        data: [],
      },
      {
        name: '指数下跌',
        data: [],
      },
    ];
    let xAxis = [];
    if (data) {
      if (data.dataSource && data.dataSource.length > 0) {
        data.dataSource.map((item) => {
          if (item.assetType == '债券资产') {
            expandedRowKeys.push(item.id);
            if (item.children && item.children.length > 0) {
              item.children.map((itemChild) => {
                if (itemChild.children && itemChild.children.length == 0) itemChild.children = null;
                xAxis.push(itemChild.assetType);
                series[0].data.push(itemChild.expectYieldLoss ? (itemChild.expectYieldLoss / 100000000).toFixed(2) : '');
                series[1].data.push(itemChild.expectBondLoss ? (itemChild.expectBondLoss / 100000000).toFixed(2) : '');
                series[2].data.push(itemChild.expectIndexLoss ? (itemChild.expectIndexLoss / 100000000).toFixed(2) : '');
              });
            }
          }
          if (item.assetType == '股票') {
            xAxis.push(item.assetType);
            series[0].data.push(item.expectYieldLoss ? (item.expectYieldLoss / 100000000).toFixed(2) : '');
            series[1].data.push(item.expectBondLoss ? (item.expectBondLoss / 100000000).toFixed(2) : '');
            series[2].data.push(item.expectIndexLoss ? (item.expectIndexLoss / 100000000).toFixed(2) : '');
          }
        });
      }
      this.setState({
        dataSource: data.dataSource,
        total: data.total.toFixed(2),
        expandedRowKeys: expandedRowKeys,
        series: series,
        xAxis: xAxis,
        needRefresh: false,
      });
    }
  };

  //修改columns的状态
  changeColumns = (columns) => {
    let data = columns;
    if (data && data.length) {
      data.map((item) => {
        if (item.key == 'expectLoss') {
          item.fixed = 'right';
          item.type = 'money';
        }
        if (
          item.key == 'denomination' ||
          item.key == 'startFullValue' ||
          item.key == 'endFullValue' ||
          item.key == 'expectYieldLoss' ||
          item.key == 'expectBondLoss' ||
          item.key == 'expectIndexLoss'
        ) {
          item.type = 'money';
        }
      });
    }
    return data;
  };

  //图标自定义提示信息
  toolTipFormat = (params) => {
    let str = `<div>`;
    str += `<div>${params[0].name}</div>`;
    params.map((item, index) => {
      if (item.data) {
        str += `${item.marker}${item.seriesName}: ${item.data}亿元`;
        str += index === params.length - 1 ? '' : '<br/>';
      }
    });
    str += '</div>';
    return str;
  };

  // 展开/收起节点时触发
  onExpand = (expanded, record) => {
    let expandedId = this.state.expandedRowKeys;
    if (expanded) {
      expandedId.push(record.id);
    } else {
      expandedId = expandedId.filter((item) => item != record.id);
    }
    this.setState({
      expandedRowKeys: expandedId,
    });
  };

  //数字处理成千分位
  changeNumber = (e) => {
    let num = e;
    if (num) {
      num = num?.replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    }
    return num;
  };

  render() {
    const { columns, dataSource, currentPage, expandedRowKeys, series, xAxis, total, count } = this.state;
    const newColumns = this.changeColumns(columns);
    return (
      <div>
        {this.props.sceneType == 2 && !count ? (
          <NoQueryC title='请先进行个券设置并开始计算' />
        ) : (
          <>
            <div className='total-top'>
              总损失：<span>{total}元</span>
            </div>
            <XYAxisChartsC
              height={240}
              series={series}
              xAxis={xAxis}
              type='barStack'
              barMaxWidth={80}
              xPosition='top'
              yAxisUnit={['单位（亿元）']}
              toolTipFormat={(params) => this.toolTipFormat(params)}
            />
            <div className='table'>
              <TableC
                columns={newColumns}
                dataSource={dataSource}
                current={currentPage}
                rowKey='id'
                scroll={{ x: 'max-content' }}
                expandedRowKeys={expandedRowKeys}
                onExpand={this.onExpand}
                hidePage={true}
                loading={this.props.loading.effects['stressSceneTestM/getStressTestList']}
              ></TableC>
            </div>
            <div className='total-bottom'>
              <span>合计</span>
              <span>{this.changeNumber(total)}</span>
            </div>
          </>
        )}
      </div>
    );
  }
}
export default connect(({ stressSceneTestM, loading }) => ({
  stressSceneTestM,
  loading,
}))(StressTest);
